import useStore  from '@/store';
import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '@/views/layout/index.vue'
import Home from '@/views/home/index.vue'
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      component: Layout,
      // 二级路由
      children: [
        // 首页
        {
          path: '',
          component: Home
        },
        // 一级分类 
        {
          path: '/category/:id', // 动态参数
          component: () => import('@/views/category/index.vue')
        },
        // 二级分类
        {
          path: '/category/sub/:id', // 动态参数
          component: () => import('@/views/category/sub.vue')
        },
        // 商品详情
        {
          path: '/goods/:id',
          component: () => import('@/views/goods/index.vue')
        },
        // 购物车
        {
          path: '/cart',
          component: () => import('@/views/cart/index.vue')
        },
        // 结算页面
        {
          path: '/member/checkout',
          component: () => import('@/views/member/pay/checkout.vue')
        },
        // 订单页面
        {
          path: '/member/pay',
          component: () => import('@/views/member/pay/index.vue')
        },
        // 支付后的回跳页面
        {
          path: '/pay/callback',
          component: () => import('@/views/member/pay/callback.vue')
        }
      ]
    },
    {
      path: '/login',
      component: () => import('@/views/login/index.vue')
    },
    {
      path: '/demo',
      component:() => import('@/views/demo/index.vue')
    }
  ],
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { top: 0 }
  },
})

// 配置路由导航守卫 -  以/member开头  /member/checkout  /member/index  /member/pay
// 判断依据: 路径中是否包含/member
// includes 数组/字符串
router.beforeEach((to, from, next) => {
  const { cart } = useStore()
  // 是否登录
  if (cart.isLogin) {
    next()
  } else {
    // 未登录
    if (to.path.includes('/member')) {
      // 访问的就是个人中心相关的一些页面 - 拦截的处理
      // next('/login')
      next({
        path: '/login',
        // query  将参数 拼接在地址栏 - 刷新不会丢失
        // params 将参数 保存在内存中 - 刷新一定会丢失
        query: {
          redirectUrl: to.fullPath
        }
      })
    } else {
      next()
    }
  }
})
export default router